/**
 * 智能文档管理API接口
 */

import type {
  DocumentCategory,
  DocumentTag,
  PersonalDocument,
  DocumentListParams,
  DocumentListResponse,
  DocumentComplianceRelation,
  FileTypeInfo,
  DocumentStatistics,
  CategoryStatistics,
} from '@/types/document';
import { typedHttp } from '@/utils/typedHttp';

// ==================== 分类管理API ====================

/**
 * 获取分类树
 */
export const fetchCategoryTree = async (): Promise<DocumentCategory[]> => {
  return typedHttp.get<DocumentCategory[]>('/document-categories/');
};

/**
 * 创建分类
 */
export const createCategory = async (data: {
  name: string;
  icon?: string;
  color?: string;
  description?: string;
  parent_id?: string | null;
}): Promise<DocumentCategory> => {
  return typedHttp.post<DocumentCategory>('/document-categories/', data);
};

/**
 * 更新分类
 */
export const updateCategory = async (id: string, data: {
  name?: string;
  icon?: string;
  color?: string;
  description?: string;
  parent_id?: string | null;
}): Promise<DocumentCategory> => {
  return typedHttp.put<DocumentCategory>(`/document-categories/${id}`, data);
};

/**
 * 删除分类
 */
export const deleteCategory = async (id: string, targetCategoryId?: string): Promise<{ message: string }> => {
  const data = targetCategoryId ? { target_category_id: targetCategoryId } : undefined;
  return typedHttp.delete<{ message: string }>(`/document-categories/${id}`, {
    data,
  } as any);
};

/**
 * 初始化系统预设分类
 */
export const initSystemCategories = async (): Promise<{ message: string }> => {
  return typedHttp.post<{ message: string }>('/document-categories/initialize-system-categories');
};

/**
 * 获取分类统计
 */
export const fetchCategoryStatistics = async (): Promise<CategoryStatistics> => {
  return typedHttp.get<CategoryStatistics>('/document-categories/statistics');
};


/**
 * 获取所有标签
 */
export const fetchAllTags = async (includeCount = false): Promise<DocumentTag[]> => {
  return typedHttp.get<DocumentTag[]>(`/document-tags/?include_count=${includeCount}`);
};

/**
 * 创建标签
 */
export const createTag = async (data: {
  name: string;
  description?: string;
  color?: string;
}): Promise<DocumentTag> => {
  return typedHttp.post<DocumentTag>('/document-tags', data);
};

/**
 * 更新标签
 */
export const updateTag = async (id: string, data: {
  name?: string;
  description?: string;
  color?: string;
}): Promise<DocumentTag> => {
  return typedHttp.put<DocumentTag>(`/document-tags/${id}`, data);
};

/**
 * 删除标签
 */
export const deleteTag = async (id: string): Promise<{ message: string }> => {
  return typedHttp.delete<{ message: string }>(`/document-tags/${id}`);
};

/**
 * 搜索标签
 */
export const searchTags = async (query: string, limit = 10): Promise<DocumentTag[]> => {
  return typedHttp.get<DocumentTag[]>(`/document-tags/search?search_term=${encodeURIComponent(query)}&limit=${limit}`);
};

/**
 * 获取热门标签
 */
export const fetchPopularTags = async (limit = 10): Promise<DocumentTag[]> => {
  return typedHttp.get<DocumentTag[]>(`/document-tags/popular?limit=${limit}`);
};

// ==================== 文档管理API ====================

/**
 * 获取文档列表
 */
export const fetchDocuments = async (params: DocumentListParams): Promise<DocumentListResponse> => {
  const searchParams = new URLSearchParams();
  
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null) {
      if (Array.isArray(value)) {
        value.forEach(v => searchParams.append(key, v.toString()));
      } else {
        searchParams.append(key, value.toString());
      }
    }
  });

  return typedHttp.get<DocumentListResponse>(`/personal-documents/?${searchParams.toString()}`);
};

/**
 * 上传文档
 */
export const uploadDocument = async (formData: FormData): Promise<PersonalDocument> => {
  // 后端返回的数据结构是 { document: PersonalDocument, message: string }
  // 需要提取其中的 document 属性
  interface UploadResponse {
    document: PersonalDocument;
    message: string;
  }
  
  const response = await typedHttp.post<UploadResponse>('/personal-documents/upload', formData, {
    headers: {
      // 不设置 Content-Type，让浏览器自动设置 multipart/form-data
    },
  });
  
  return response.document;
};

/**
 * 获取文档详情
 */
export const fetchDocumentDetail = async (id: string): Promise<PersonalDocument> => {
  return typedHttp.get<PersonalDocument>(`/personal-documents/${id}`);
};

/**
 * 更新文档
 */
export const updateDocument = async (id: string, data: {
  title?: string;
  description?: string;
  category_id?: string | null;
  tags?: string[];
}): Promise<PersonalDocument> => {
  return typedHttp.put<PersonalDocument>(`/personal-documents/${id}`, data);
};

/**
 * 删除文档
 */
export const deleteDocument = async (id: string): Promise<{ message: string }> => {
  return typedHttp.delete<{ message: string }>(`/personal-documents/${id}`);
};

/**
 * 切换收藏状态
 */
export const toggleFavorite = async (id: string): Promise<PersonalDocument> => {
  return typedHttp.post<PersonalDocument>(`/personal-documents/${id}/favorite`);
};

/**
 * 切换置顶状态
 */
export const togglePin = async (id: string): Promise<PersonalDocument> => {
  return typedHttp.post<PersonalDocument>(`/personal-documents/${id}/pin`);
};

/**
 * 批量删除文档
 */
export const batchDeleteDocuments = async (documentIds: string[]): Promise<{ deleted_count: number; message: string }> => {
  return typedHttp.post<{ deleted_count: number; message: string }>('/personal-documents/batch-delete', {
    document_ids: documentIds,
  });
};

/**
 * 批量移动文档
 */
export const batchMoveDocuments = async (documentIds: string[], categoryId: string | null): Promise<{ moved_count: number; message: string }> => {
  return typedHttp.post<{ moved_count: number; message: string }>('/personal-documents/batch-move', {
    document_ids: documentIds,
    category_id: categoryId,
  });
};

/**
 * 获取收藏文档
 */
export const fetchFavoriteDocuments = async (limit = 10): Promise<PersonalDocument[]> => {
  return typedHttp.get<PersonalDocument[]>(`/personal-documents/favorites/list?limit=${limit}`);
};

/**
 * 获取最近访问文档
 */
export const fetchRecentDocuments = async (limit = 10): Promise<PersonalDocument[]> => {
  return typedHttp.get<PersonalDocument[]>(`/personal-documents/recent/list?limit=${limit}`);
};

/**
 * 获取文档统计
 */
export const fetchDocumentStatistics = async (): Promise<DocumentStatistics> => {
  return typedHttp.get<DocumentStatistics>('/personal-documents/statistics/overview');
};

/**
 * 获取文件类型信息
 */
export const fetchFileTypes = async (): Promise<Record<string, FileTypeInfo>> => {
  return typedHttp.get<Record<string, FileTypeInfo>>('/personal-documents/file-types/info');
};

// ==================== 文档与检查项关联API ====================

/**
 * 创建文档与检查项关联
 */
export const createDocumentRelation = async (data: {
  document_id: string;
  compliance_template_item_id: string;
  relation_type?: 'evidence' | 'reference' | 'template';
  description?: string;
}): Promise<DocumentComplianceRelation> => {
  return typedHttp.post<DocumentComplianceRelation>('/document-relations/compliance', data);
};

/**
 * 批量创建文档与检查项关联
 */
export const batchCreateDocumentRelations = async (relations: {
  document_id: string;
  compliance_template_item_id: string;
  relation_type?: 'evidence' | 'reference' | 'template';
  description?: string;
}[]): Promise<{ created_count: number; skipped_count: number; message: string }> => {
  return typedHttp.post<{ created_count: number; skipped_count: number; message: string }>('/document-relations/compliance/batch', {
    relations,
  });
};

/**
 * 获取文档关联的检查项
 */
export const fetchDocumentRelations = async (documentId: string): Promise<DocumentComplianceRelation[]> => {
  return typedHttp.get<DocumentComplianceRelation[]>(`/document-relations/compliance/document/${documentId}`);
};

/**
 * 获取检查项关联的文档
 */
export const fetchTemplateItemRelations = async (templateItemId: string): Promise<DocumentComplianceRelation[]> => {
  return typedHttp.get<DocumentComplianceRelation[]>(`/document-relations/compliance/template-item/${templateItemId}`);
};

/**
 * 按关联类型查询
 */
export const fetchRelationsByType = async (relationType: 'evidence' | 'reference' | 'template'): Promise<DocumentComplianceRelation[]> => {
  return typedHttp.get<DocumentComplianceRelation[]>(`/document-relations/compliance/type/${relationType}`);
};

/**
 * 删除文档与检查项关联
 */
export const deleteDocumentRelation = async (relationId: string): Promise<{ message: string }> => {
  return typedHttp.delete<{ message: string }>(`/document-relations/compliance/${relationId}`);
};

/**
 * 删除文档的所有关联
 */
export const deleteDocumentAllRelations = async (documentId: string): Promise<{ deleted_count: number; message: string }> => {
  return typedHttp.delete<{ deleted_count: number; message: string }>(`/document-relations/compliance/document/${documentId}`);
};

/**
 * 删除检查项的所有关联
 */
export const deleteTemplateItemAllRelations = async (templateItemId: string): Promise<{ deleted_count: number; message: string }> => {
  return typedHttp.delete<{ deleted_count: number; message: string }>(`/document-relations/compliance/template-item/${templateItemId}`);
};
